package com.sunfeng.n4.crossoutput;

import lombok.extern.slf4j.Slf4j;

/**
 * 线程1输出a 线程2输出b 线程3输出c
 *
 * @author sunfeng
 * @date 2021/03/30 14:50
 **/

@Slf4j(topic = "c.SyncWaitNotify")
public class SyncWaitNotifyTest {
    public static void main(String[] args) {
        SyncWaitNotify syncWaitNotify = new SyncWaitNotify(1, 10);

        new Thread(() -> {
            syncWaitNotify.print("a", 1, 2);
        }).start();
        new Thread(() -> {
            syncWaitNotify.print("b", 2, 3);
        }).start();
        new Thread(() -> {
            syncWaitNotify.print("c", 3, 1);
        }).start();
    }

}

class SyncWaitNotify {
    private int flag;

    private int countOutPut;

    public SyncWaitNotify(int flag, int countOutPut) {
        this.flag = flag;
        this.countOutPut = countOutPut;
    }

    /**
     * 这一段代码很难懂啊
     *
     * @param str
     * @param waitFlag
     * @param nextFlag
     */
    public void print(String str, int waitFlag, int nextFlag) {
        for (int i = 0; i < countOutPut; i++) {
            synchronized (this) {
                while (flag != waitFlag) {
                    try {
                        this.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
                System.out.print(str);
                flag = nextFlag;

                this.notifyAll();
            }
        }
    }

}